package com.ds.infrastructure.audit.admin.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.ds.infrastructure.audit.admin.constant.AdminConstant;
import com.ds.infrastructure.audit.admin.enums.PageType;
import com.ds.infrastructure.audit.admin.service.IAdminService;
import com.ds.infrastructure.audit.admin.vo.DefaultResponseVO;
import com.ds.infrastructure.audit.admin.vo.IndexQueryPageVO;
import com.ds.infrastructure.audit.admin.vo.IndexQueryVO;
import com.ds.infrastructure.audit.admin.vo.KbaBehaviorVO;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 作用：
 *
 * @author WeiShaoying
 * @date 2020/8/6
 */
@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {

    @Value("${search-platform.url}")
    private String url;

    @Value("${search-platform.timeout}")
    private int timeout;

    private String searchUrl;

    @PostConstruct
    private void init() {
        searchUrl = url + AdminConstant.SEARCH_API_URL;
        log.info("Search Platform url = {}", searchUrl);
    }

    /**
     * 搜索
     *
     * @param vo
     * @return
     */
    @Override
    public DefaultResponseVO searchBehavior(KbaBehaviorVO vo) {
        Map<String, Object> mapFilter = Maps.newHashMapWithExpectedSize(10);
        Map<String, Object> mapMatch = Maps.newHashMapWithExpectedSize(6);
        IndexQueryVO.IndexQueryVOBuilder builder = IndexQueryVO.builder()
                .appKey(AdminConstant.SearchTest.APP_KEY_TEST)
                .type(AdminConstant.SearchTest.TYPE);
        Integer pageSize = vo.getPageSize();
        Integer pageNo = vo.getPageNum();
        if (hasValue(pageSize) && hasValue(pageNo)) {
            IndexQueryPageVO.IndexQueryPageVOBuilder pageBuilder = IndexQueryPageVO.builder();
            pageBuilder.from((pageNo - 1) * pageSize);
            pageBuilder.size(pageSize);
            int total = pageSize * pageNo;
            if (total > AdminConstant.DEEP_PAGE_NUM) {
                pageBuilder.pageType(PageType.DEEP.name().toLowerCase());
            } else {
                pageBuilder.pageType(PageType.SIMPLE.name().toLowerCase());
            }
            pageBuilder.sort(vo.getSortList());
            pageBuilder.previousSortLastValues(vo.getPreviousSortLastValues());
            builder.page(pageBuilder.build());
        }

        String appName = vo.getAppName();
        if (StringUtils.isNotBlank(appName)) {
            mapFilter.put("appName", appName);
        }
        String groupId = vo.getGroupId();
        if (StringUtils.isNotBlank(groupId)) {
            mapFilter.put("groupId", groupId);
        }
        String shopId = vo.getShopId();
        if (StringUtils.isNotBlank(shopId)) {
            mapFilter.put("shopId", shopId);
        }
        String bizName = vo.getBizName();
        if (StringUtils.isNotBlank(bizName)) {
            mapMatch.put("bizName", bizName);
        }

        String behaviorId = vo.getBehaviorId();
        if (StringUtils.isNotBlank(behaviorId)) {
            mapFilter.put("behaviorId", behaviorId);
        }

        String action = vo.getAction();
        if (StringUtils.isNotBlank(action)) {
            mapMatch.put("action", action);
        }
        String actionDetail = vo.getActionDetail();
        if (StringUtils.isNotBlank(actionDetail)) {
            mapMatch.put("actionDetail", actionDetail);
        }
        String userId = vo.getUserId();
        if (StringUtils.isNotBlank(userId)) {
            mapFilter.put("userId", userId);
        }
        String extra = vo.getExtra();
        if (StringUtils.isNotBlank(extra)) {
            mapMatch.put("extra", extra);
        }

        Integer startPriority = vo.getStartPriority();
        Integer endPriority = vo.getEndPriority();
        boolean bStartPriority = hasValue(startPriority);
        boolean bEndPriority = hasValue(endPriority);
        if (bStartPriority && bEndPriority) {
            mapFilter.put("priority", "range[" + startPriority + "," + endPriority + "]");
        } else if (bStartPriority) {
            mapFilter.put("priority", "range[" + startPriority + ",*]");
        } else if (bEndPriority) {
            mapFilter.put("priority", "range[*," + endPriority + "]");
        }

        Long startTime = vo.getStartTime();
        Long endTime = vo.getEndTime();
        boolean bStartTime = hasValue(startTime);
        boolean bEndTime = hasValue(endTime);
        if (bStartTime && bEndTime) {
            mapFilter.put("createTime", "range[" + startTime + "," + endTime + "]");
        } else if (bStartTime) {
            mapFilter.put("createTime", "range[" + startTime + ",*]");
        } else if (bEndTime) {
            mapFilter.put("createTime", "range[*," + endTime + "]");
        }

        if (MapUtil.isNotEmpty(mapFilter)) {
            builder.filter(mapFilter);
        }
        if (MapUtil.isNotEmpty(mapMatch)) {
            builder.match(mapMatch);
        }
        IndexQueryVO queryVO = builder.build();
        try {
            String response = HttpUtil.post(searchUrl, JSON.toJSONString(queryVO), timeout);
            log.info("搜索={}", response);
            return JSONUtil.toBean(response, DefaultResponseVO.class);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private boolean hasValue(Integer integer) {
        return integer != null && integer > 0;
    }

    private boolean hasValue(Long v) {
        return v != null && v > 0;
    }

}
